<#
.SYNOPSIS
  Generate style templates based on existing project structure (Java/Python).

.DESCRIPTION
  Scans src directories to infer basic style signals (package base, annotations)
  and produces template files with placeholders under .tmp/style_templates.
  Optionally applies them into templates/<lang>/style.

.PARAMETER Lang
  Target language: 'java' or 'python'. Default: 'java'.

.PARAMETER Apply
  If specified, copy generated templates into templates/<lang>/style.

.EXAMPLE
  pwsh -NoProfile -File scripts/windows/gen-style-templates.ps1 -Lang java -Apply

.NOTES
  This is a native PowerShell implementation to mirror Python CLI behavior.
#>

param(
  [string]$Lang = "java",
  [switch]$Apply
)

$ErrorActionPreference = "Stop"

function Get-RepoRoot {
  $scriptPath = Split-Path -Parent $MyInvocation.MyCommand.Path
  return (Split-Path -Parent $scriptPath)
}

function Ensure-Dir($path) {
  if (-not (Test-Path -Path $path)) { New-Item -ItemType Directory -Force -Path $path | Out-Null }
}

$root = Get-RepoRoot
$outBase = Join-Path $root ".tmp/style_templates"
Ensure-Dir $outBase

if ($Lang -eq "java") {
  $srcDir = Join-Path $root "src/main/java"
  if (-not (Test-Path $srcDir)) { $srcDir = $null }

  $pkgCounts = @{}
  $flags = @{ rest_controller=$false; controller=$false; service=$false; repository=$false }

  if ($srcDir) {
    Get-ChildItem -Path $srcDir -Recurse -Filter *.java | ForEach-Object {
      $t = Get-Content -Path $_.FullName -Raw -ErrorAction Ignore
      $m = [regex]::Match($t, '^\s*package\s+([\w\.]+);', 'Multiline')
      if ($m.Success) {
        $pkg = $m.Groups[1].Value
        if ($pkgCounts.ContainsKey($pkg)) { $pkgCounts[$pkg] += 1 } else { $pkgCounts[$pkg] = 1 }
      }
      if ($t -match '@RestController') { $flags.rest_controller = $true }
      if ($t -match '@Controller') { $flags.controller = $true }
      if ($t -match '@Service') { $flags.service = $true }
      if ($t -match '@Repository') { $flags.repository = $true }
    }
  }

  $package = if ($pkgCounts.Keys.Count -gt 0) { ($pkgCounts.GetEnumerator() | Sort-Object -Property Value -Descending | Select-Object -First 1).Key } else { "com.example" }
  $outDir = Join-Path $outBase "java"
  Ensure-Dir $outDir

  $header = "/*`n Generated style template. Placeholders:`n  - {{PACKAGE}} base package`n  - {{ClassName}}`n*/`n"
  $ctrlAnno = if ($flags.rest_controller) { "@RestController" } elseif ($flags.controller) { "@Controller" } else { "" }

  Set-Content -Path (Join-Path $outDir "Controller.java.tmpl") -Encoding UTF8 -Value @"
$header
package {{PACKAGE}};

$ctrlAnno
public class {{ClassName}}Controller {
    public {{ClassName}}Controller() {}
}
"@

  Set-Content -Path (Join-Path $outDir "Service.java.tmpl") -Encoding UTF8 -Value @"
$header
package {{PACKAGE}};

@Service
public class {{ClassName}}Service {
    public {{ClassName}}Service() {}
}
"@

  Set-Content -Path (Join-Path $outDir "Repository.java.tmpl") -Encoding UTF8 -Value @"
$header
package {{PACKAGE}};

@Repository
public interface {{ClassName}}Repository {
}
"@

  Set-Content -Path (Join-Path $outDir "Entity.java.tmpl") -Encoding UTF8 -Value @"
$header
package {{PACKAGE}};

public class {{ClassName}} {
    // TODO: fields
}
"@

  Set-Content -Path (Join-Path $outDir "Dto.java.tmpl") -Encoding UTF8 -Value @"
$header
package {{PACKAGE}};

public class {{ClassName}}Dto {
    // TODO: fields
}
"@

  Set-Content -Path (Join-Path $outDir "Vo.java.tmpl") -Encoding UTF8 -Value @"
$header
package {{PACKAGE}};

public class {{ClassName}}Vo {
    // TODO: fields
}
"@

  Write-Host "[gen-style-templates] java -> $outDir package=$package"

  if ($Apply) {
    $target = Join-Path $root "templates/java/style"
    Ensure-Dir $target
    Get-ChildItem -Path $outDir -Filter *.tmpl | ForEach-Object {
      Copy-Item -Path $_.FullName -Destination (Join-Path $target $_.Name) -Force
    }
    Write-Host "[gen-style-templates] applied -> $target"
  }
}
elseif ($Lang -eq "python") {
  $outDir = Join-Path $outBase "python"
  Ensure-Dir $outDir
  $header = "\"\"\"`nGenerated style template. Placeholders:`n  - {{ModuleName}} / {{ClassName}}`n\"\"\"`n"

  function Write-PyTmpl($rel, $content) {
    $p = Join-Path $outDir $rel
    $parent = Split-Path -Parent $p
    Ensure-Dir $parent
    Set-Content -Path $p -Encoding UTF8 -Value $content
  }

  Write-PyTmpl "ddd/application/service.py.tmpl" @"
$header
class {{ClassName}}Service:
    def __init__(self):
        pass
"@

  Write-PyTmpl "ddd/domain/model.py.tmpl" @"
$header
class {{ClassName}}:
    def __init__(self):
        pass
"@

  Write-PyTmpl "ddd/infrastructure/repository.py.tmpl" @"
$header
class {{ClassName}}Repository:
    def save(self, obj):
        raise NotImplementedError
"@

  Write-PyTmpl "ddd/interfaces/controller.py.tmpl" @"
$header
class {{ClassName}}Controller:
    def handle(self, req):
        pass
"@

  Write-Host "[gen-style-templates] python -> $outDir"

  if ($Apply) {
    $target = Join-Path $root "templates/python/style"
    Get-ChildItem -Path $outDir -Recurse -Filter *.tmpl | ForEach-Object {
      $rel = $_.FullName.Substring($outDir.Length + 1)
      $dst = Join-Path $target $rel
      $parent = Split-Path -Parent $dst
      Ensure-Dir $parent
      Copy-Item -Path $_.FullName -Destination $dst -Force
    }
    Write-Host "[gen-style-templates] applied -> $target"
  }
}
else {
  Write-Error "[gen-style-templates] unsupported lang. use: java|python"
  exit 2
}

exit 0
